package org.gis.mapserver.layer;

import java.util.Map;
import org.gis.mapserver.base.ConfigBean;
import org.gis.mapserver.source.SourceFactory;
import org.gis.utils.activator.Activator;
import org.gis.utils.beanloader.ConfigBeanLoader;
import org.gis.dbtools.UniqueID;

/**
 *
 * @author gus
 */
public final class LayerFactory
{
    private Map<String, String> layerMapping;
    private SourceFactory sourceFactory;
    private ConfigBeanLoader configBeanLoader;

    public ConfigBeanLoader getConfigBeanLoader()
    {
        return configBeanLoader;
    }

    public void setConfigBeanLoader( ConfigBeanLoader configBeanLoader )
    {
        this.configBeanLoader = configBeanLoader;
    }

    public void setSourceFactory( SourceFactory sourceFactory )
    {
        this.sourceFactory = sourceFactory;
    }

    public void setLayerMapping( Map<String, String> layerMapping )
    {
        this.layerMapping = layerMapping;
    }

    public Layer creatLayer( String layerName, boolean enable ) throws Exception
    {
        String typeName = getTypeName(layerName);
        if ( typeName == null )
        {
            throw new Exception(String.format("Can`t found layer ", layerName));
        }

        Layer layer = (Layer) Activator.instance(typeName);
        layer.setSourceFactory(sourceFactory);
        layer.setLayerConfigBean(loadLayerConfigBean(layer.getLayerType()));
        layer.setEnabled(enable);
        layer.setName(layerName);
        layer.afterInitialize();

        return layer;
    }

    private String getTypeName( String layerName )
    {
        return layerMapping.get(layerName);
    }

    private ConfigBean loadLayerConfigBean( UniqueID uid ) throws Exception
    {
        return configBeanLoader.loadConfigBean(uid);
    }
}
